/**
 * Copyright (C) 2013 Oleg Anastassov <oleg.anastassov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.loc.desktop.run;

import kz.kstu.loc.desktop.controls.factory.ComponentFactory;
import kz.kstu.loc.desktop.controls.factory.ImageFactory;
import kz.kstu.loc.desktop.dialogs.ADialog;
import kz.kstu.loc.desktop.dialogs.AboutDialog;
import kz.kstu.loc.desktop.dialogs.SettingsDialog;
import kz.kstu.loc.desktop.icon.GUIIcon;
import kz.kstu.loc.util.GUIUtils;
import kz.kstu.loc.util.StringUtils;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: 23.01.2013
 * Time: 17:10
 *
 * @author Oleg Anastassov
 */
public class AppDashboard extends JFrame {

    private static final String TITLE = "Локализатор";

    private static final String LOC_TOOL_CURRENT_DIR = "loc.tool.current.dir";

    private static final int WIDTH = 1000;
    private static final int HEIGHT = 500;

    private JMenuItem chooseDir;
    private JMenuItem commonsMenuItem;
    private JMenuItem toXLSMenuItem;
    private JMenuItem fromXLSMenuItem;
    private JMenuItem exitMenuItem;
    private JMenuItem aboutMenuItem;

    private JTree tree;

    public AppDashboard() {
        initWindow();
        initStaticComponents();
        initListeners();
        initAccelerators();
    }

    private void initWindow() {
        setIconImage(ImageFactory.createImage(GUIIcon.LOGO));
        setTitle(TITLE);
        setSize(new Dimension(WIDTH, HEIGHT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private void initStaticComponents() {
        setJMenuBar(getMainMenuBar());


        tree = new JTree(addNodes(null, new File(".")));
        tree.setPreferredSize(new Dimension(250, 100));
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.getViewport().add(tree);
//        add(BorderLayout.WEST, scrollPane);


        String[] columnNames = {
                "Ключ", "Значение на русском", "Значение на казахском"
        };

        Object[][] data = {
                {"TS_KEY_1", "Ключ №1", "Кiлт №1"},
                {"TS_KEY_2", "Ключ №2", "Кiлт №2"},
                {"TS_KEY_3", "Ключ №3", "Кiлт №3"}
        };

//        add(BorderLayout.CENTER, new JScrollPane(new JTable(data, columnNames)));

        //Create a split pane with the two scroll panes in it.
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                scrollPane, new JScrollPane(new JTable(data, columnNames)));
        splitPane.setOneTouchExpandable(true);
        splitPane.setDividerLocation(300);
        add(splitPane);

        JPanel statusBar = new JPanel(new GridLayout());
        statusBar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
        statusBar.add(new JLabel("Status bar"));
        add(BorderLayout.SOUTH, statusBar);
    }

    private JMenuBar getMainMenuBar() {
        JMenuBar bar = new JMenuBar();

        // меню "Файл"
        JMenu fileMenu = new JMenu("Файл");
        fileMenu.setIcon(ImageFactory.createIcon(GUIIcon.FILE));
        chooseDir = ComponentFactory.createMenuItem("Выбрать каталог...", GUIIcon.BROWSE);
        exitMenuItem = ComponentFactory.createMenuItem("Выход", GUIIcon.EXIT);
        fileMenu.add(chooseDir);
//        fileMenu.add(patchMenuItem);
        fileMenu.addSeparator();
        fileMenu.add(exitMenuItem);
        bar.add(fileMenu);

        // Выгрузить
        JMenu exportMenu = ComponentFactory.createMenu("Выгрузить", GUIIcon.EXTRACT);
        toXLSMenuItem = ComponentFactory.createMenuItem("В Excel (XLS)..", GUIIcon.EXCEL);
        exportMenu.add(toXLSMenuItem);
        bar.add(exportMenu);

        // Загрузить
        JMenu load = new JMenu("Загрузить");
        load.setIcon(ImageFactory.createIcon(GUIIcon.PATCH));
        fromXLSMenuItem = ComponentFactory.createMenuItem("Из Excel (XLS)..", GUIIcon.EXCEL);
        load.add(fromXLSMenuItem);
        bar.add(load);

        // меню "Настройки"
        JMenu settingsMenu = new JMenu("Настройки");
        settingsMenu.setIcon(ImageFactory.createIcon(GUIIcon.SETTINGS));
        commonsMenuItem = new JMenuItem("Общие..", ImageFactory.createIcon(GUIIcon.COMMONS));
        settingsMenu.add(commonsMenuItem);
        bar.add(settingsMenu);

        // меню "Помощь"
        JMenu helpMenu = new JMenu("Помощь");
        helpMenu.setIcon(ImageFactory.createIcon(GUIIcon.HELP));
        aboutMenuItem = ComponentFactory.createMenuItem("О программе..", GUIIcon.ABOUT);
        helpMenu.add(aboutMenuItem);
        bar.add(helpMenu);
        return bar;
    }

    private void initListeners() {
        chooseDir.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File dir = chooseDirectory();
                // TODO: На время тестирования закомментировал
                // fillTree(dir);
            }
        });
        commonsMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ADialog dialog = new SettingsDialog();
                GUIUtils.centerAndShow(dialog);
            }
        });
        exitMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        aboutMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AboutDialog dialog = new AboutDialog();
                GUIUtils.centerAndShow(dialog);
            }
        });
    }

    private File chooseDirectory() {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setAcceptAllFileFilterUsed(false);

        String workDir = System.getProperty(LOC_TOOL_CURRENT_DIR);
        if (!StringUtils.isEmptyOrNull(workDir)) {
            fc.setCurrentDirectory(new File(workDir));
        }

        int result = fc.showOpenDialog(getContentPane());
        if (result == JFileChooser.APPROVE_OPTION) {
            System.setProperty(
                    LOC_TOOL_CURRENT_DIR, fc.getSelectedFile().getAbsolutePath()
            );
            return fc.getCurrentDirectory();
        }
        return fc.getCurrentDirectory();
    }

    private void fillTree(File dir) {
        if (dir.exists()) {
            DefaultMutableTreeNode nodes = addNodes(null, dir);

            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
            root.removeAllChildren();
            root.add(nodes);
            model.reload(root);
        }
    }

    private DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
        String curPath = dir.getPath();
        DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
        if (curTop != null) { // root
            curTop.add(curDir);
        }
        List<String> ol = new ArrayList<String>();
        String[] tmp = dir.list();
        for (String aTmp : tmp) {
            ol.add(aTmp);
        }
//        Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
        File f;
        List files = new ArrayList();
        for (int i = 0; i < ol.size(); i++) {
            String thisObject = ol.get(i);
            String newPath;
            if (curPath.equals("."))
                newPath = thisObject;
            else
                newPath = curPath + File.separator + thisObject;
            if ((f = new File(newPath)).isDirectory() && !(f = new File(newPath)).isHidden())
                addNodes(curDir, f);
            else if (!(f = new File(newPath)).isHidden())
                files.add(thisObject);
        }
        // Pass two: for files.
        for (Object file : files) {
            curDir.add(new DefaultMutableTreeNode(file));
        }
        return curDir;
    }

    private void initAccelerators() {
        chooseDir.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK)
        );
        toXLSMenuItem.setAccelerator(
                KeyStroke.getKeyStroke("control alt E")
        );
        fromXLSMenuItem.setAccelerator(
                KeyStroke.getKeyStroke("control alt P")
        );
        commonsMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK)
        );
        exitMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK)
        );
        aboutMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)
        );
    }


}